package com.wjl.picture.common.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.wjl.picture.common.config.CosClientConfig;
import com.wjl.picture.common.exception.BusinessException;
import com.wjl.picture.common.exception.ErrorCode;
import com.wjl.picture.common.manager.CosManager;
import com.wjl.picture.picture.model.dto.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


@Slf4j
public abstract class PictureUploadTemplate {  
  
    @Resource
    protected CosManager cosManager;
  
    @Resource  
    protected CosClientConfig cosClientConfig;
  
    /**  
     * 模板方法，定义上传流程  
     */  
    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1. 校验图片  
        validPicture(inputSource);  
  
        // 2. 图片上传地址  
        String uuid = RandomUtil.randomString(16);
        String originFilename = getOriginFilename(inputSource);
        String suffix = FileUtil.getSuffix(originFilename);

        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                suffix);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
  
        File file = null;
        try {  
            // 3. 创建临时文件  
            file = File.createTempFile(uploadPath, null);  
            // 处理文件来源（本地或 URL）  
            processFile(inputSource, file);
            if (StrUtil.isBlank(suffix)){
                suffix = getImageFormatExtension(file);
                uploadPath = String.format("%s%s", uploadPath, suffix);
            }

            // 4. 上传图片到对象存储  
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            List<CIObject> objectList = putObjectResult.getCiUploadResult().getProcessResults().getObjectList();
            CIObject compressedCiObject=null;
            CIObject thumbenailCiObject=null;
            if(CollUtil.isNotEmpty(objectList)){
                 compressedCiObject = objectList.get(0);
                 thumbenailCiObject = objectList.get(1);
            }
            // 5. 封装返回结果  
            return buildResult(originFilename, file, uploadPath, imageInfo,compressedCiObject,thumbenailCiObject);
        } catch (Exception e) {  
            log.error("图片上传到对象存储失败", e);  
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {  
            // 6. 清理临时文件  
            deleteTempFile(file);  
        }  
    }

    public static String getImageFormatExtension(File imageFile) throws IOException {
        // 获取图片文件的输入流
        ImageInputStream iis = ImageIO.createImageInputStream(imageFile);

        // 获取支持的图片读取器
        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);

        // 如果存在合适的读取器，获取文件格式
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            String formatName = reader.getFormatName().toLowerCase();  // 获取格式名并转为小写
            return getExtensionFromFormat(formatName);
        }

        // 如果没有匹配的格式，返回null
        return null;
    }
    // 根据图片格式返回对应的文件扩展名
    private static String getExtensionFromFormat(String formatName) {
        switch (formatName) {
            case "jpg":
            case "jpeg":
                return "jpg";
            case "png":
                return "png";
            case "gif":
                return "gif";
            case "bmp":
                return "bmp";
            case "tiff":
                return "tiff";
            case "webp": // 新增 WebP 格式
                return "webp";
            default:
                return null;
        }
    }
  
    /**  
     * 校验输入源（本地文件或 URL）  
     */  
    protected abstract void validPicture(Object inputSource);  
  
    /**  
     * 获取输入源的原始文件名  
     */  
    protected abstract String getOriginFilename(Object inputSource);  
  
    /**  
     * 处理输入源并生成本地临时文件  
     */  
    protected abstract void processFile(Object inputSource, File file) throws Exception;  
  
    /**  
     * 封装返回结果  
     */  
    private UploadPictureResult buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo, CIObject compressedCiObject, CIObject thumbenailCiObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();  
        int picWidth = imageInfo.getWidth();  
        int picHeight = imageInfo.getHeight();  
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));  
        uploadPictureResult.setPicWidth(picWidth);  
        uploadPictureResult.setPicHeight(picHeight);  
        uploadPictureResult.setPicScale(picScale);  
        uploadPictureResult.setPicFormat(imageInfo.getFormat());  
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicColor(imageInfo.getAve());
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        if (thumbenailCiObject!= null) {
            uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbenailCiObject.getKey());
        }else{
            uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        }
        return uploadPictureResult;  
    }  
  
    /**  
     * 删除临时文件  
     */  
    public void deleteTempFile(File file) {  
        if (file == null) {  
            return;  
        }  
        boolean deleteResult = file.delete();  
        if (!deleteResult) {  
            log.error("file delete error, filepath = {}", file.getAbsolutePath());  
        }  
    }  
}
